<template>
  <div ref="wrapEl">
    <!--引用表格-->
   <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <template #fapiaopathSlot="{ record }"> 
          <div class="ant-table-cell-ellipsis" style="width: 100%;color:#1890ff;cursor: pointer;" :title="record.fapiaopath" @click="handleFile(record.fapiaopath)">
            {{ record.fapiaopath }}
          </div> 
      </template>
      <!--插槽:table标题-->
      <template #tableTitle>
          <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
        <a-button  type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出(普通)</a-button>
        <j-upload-button  type="primary" preIcon="ant-design:import-outlined" @click="onImportXlsExt">导入(生成收款)</j-upload-button>
          <a-button  type="primary" preIcon="ant-design:export-outlined" @click="onExportXlsForFaopiao"> 导出(开发票)</a-button>
        <!--<j-upload-button  type="primary" preIcon="ant-design:import-outlined" @click="onFAPIAOImport">发票导入</j-upload-button>
        <a-button  type="primary" preIcon="ant-design:export-outlined" @click="onFAPIAOExport"> 发票导出</a-button>-->
<!--          <a-dropdown v-if="selectedRowKeys.length > 0">
              <template #overlay>
                <a-menu>
                  <a-menu-item key="1" @click="batchHandleDelete">
                    <Icon icon="ant-design:delete-outlined"></Icon>
                    删除
                  </a-menu-item>
                </a-menu>
              </template>
              <a-button>批量操作
                <Icon icon="mdi:chevron-down"></Icon>
              </a-button>
        </a-dropdown>-->
      </template>
       <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
      </template>
      <!--字段回显插槽-->
      <template #htmlSlot="{text}">
         <div v-html="text"></div>
      </template>
      <!--省市区字段回显插槽-->
      <template #pcaSlot="{text}">
         {{ getAreaTextByCode(text) }}
      </template>
      <template #fileSlot="{text}">
         <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
         <a-button v-else :ghost="true" type="primary" preIcon="ant-design:download-outlined" size="small" @click="downloadFile(text)">下载</a-button>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <DbHireModal @register="registerModal" @success="handleSuccess"></DbHireModal>
    <component :is="currentModal" v-model:visible="modalVisible" :userData="userData" />
    <DbGlfscExportModal @register="registerExport" />
  </div>
</template>



<script lang="ts" name="assets/accountReceive/DbHireList" setup>
  import {ref, computed, unref,nextTick,shallowRef, ComponentOptions,reactive,} from 'vue';
  import {BasicTable, useTable, TableAction} from '/@/components/Table';
  import { Loading, useLoading } from '/@/components/Loading';
  import {useModal} from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage'
  import DbHireModal from './components/DbHireModal.vue'
  import {columns, searchFormSchema} from './DbHire.data';
  import {
    list,
    deleteOne,
    batchDelete,
    getImportUrl,
    getExportUrl,
    getImportFAOPIAOUrl,
    getExportFAOPIAOUrl,
    exportForOpenFapiao, listNoThenToday
  } from './DbHire.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import { useMethods } from '/@/hooks/system/useMethods';
  import {defHttp} from '/@/utils/http/axios';
  import DbGlfscExportModal from '../accountReceivable/components/DbGlfscExportModal.vue'
  import {downloadByBase64, downloadByData, downloadByUrl} from '/@/utils/file/download';
  import axios from 'axios';
  import { useGlobSetting } from '/@/hooks/setting';
  import {getToken} from "/@/utils/auth";
  import { createImgPreview } from '/@/components/Preview/index';
  import {useRouter ,useRoute } from "vue-router"
  const router = useRouter()
  const route = useRoute()

  const globSetting = useGlobSetting();
  const urlPrefix = globSetting.urlPrefix;
  const checkedKeys = ref<Array<string | number>>([]);
  //注册model
  const wrapEl = ref<ElRef>(null);
  const { handleExportXls, handleImportXls } = useMethods();
  const [registerModal, {openModal}] = useModal();
  const [registerExport, { openModal: openModalExport }] = useModal();
  //注册table数据
  const { prefixCls,tableContext,onExportXls,onImportXls } = useListPage({
      tableProps:{
           title: '实际收款',
           api: listNoThenToday,
           columns,
           canResize:false,
           formConfig: {
              //labelWidth: 120,
              schemas: searchFormSchema,
              autoSubmitOnEnter:true,
              showAdvancedButton:true,
              fieldMapToNumber: [
              ],
             fieldMapToTime: [
               ['skqx', ['skqx_begin', 'skqx_end'], 'YYYY-MM-DD'],
             ],
            },
           actionColumn: {
               width: 120,
               fixed:'right'
            },
        defSort: {
          column: 'qymc,skqx',
          order: 'desc',
        },
      },
       exportConfig: {
            name:"实际收款",
            url: getExportUrl,
          },
          importConfig: {
            url: getImportUrl,
            success: handleSuccess
          },
  })

  const [registerTable, {reload},{ rowSelection, selectedRowKeys }] = tableContext
  const modalVisible = ref<Boolean>(false);
  const currentModal = shallowRef<Nullable<ComponentOptions>>(null);
  const userData = ref<any>(null);
  const [openWrapLoading, closeWrapLoading] = useLoading({
    target: wrapEl,
    props: {
      tip: '加载中...',
      absolute: true,
    },
  });

  function onFAPIAOImport(file){

    //update-begin-author:taoyan date:20220507 for: erp代码生成 子表 导入地址是动态的
    let realUrl = typeof getImportFAOPIAOUrl === 'function' ? getImportFAOPIAOUrl() : getImportFAOPIAOUrl;
    if (realUrl) {
      return handleImportXls(file, realUrl, handleImportFAPIAOSuccess || reload);
      //update-end-author:taoyan date:20220507 for: erp代码生成 子表 导入地址是动态的
    } else {
      $message.createMessage.warn('没有传递 url 参数');
      return Promise.reject();
    }
  }
  function onImportXlsExt(e) {
    openWrapLoading();
    console.log("fjfj")
    onImportXls(e);
  }

  function onExportXlsForFaopiao(){
    currentModal.value = DbGlfscExportModal;
    nextTick(() => {
      // `useModal` not working with dynamic component
      // passing data through `userData` prop
      userData.value = {showbank:true,showsfyf:true,showqyxz:false,showsshy:false,showqymc:true,showtype:false,url:exportForOpenFapiao,title:"开发票导出" };
      modalVisible.value = true;
    });
  }


   /**
    * 新增事件
    */
  function handleAdd() {
     openModal(true, {
       isUpdate: false,
       showFooter: true,
     });
  }
   /**
    * 编辑事件
    */
  function handleEdit(record: Recordable) {
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: true,
     });
   }
   /**
    * 详情
   */
  function handleDetail(record: Recordable) {
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: false,
     });
   }
   /**
    * 删除事件
    */
  async function handleDelete(record) {
     await deleteOne({id: record.id}, handleSuccess);
   }
   /**
    * 批量删除事件
    */
  async function batchHandleDelete() {
     await batchDelete({ids: selectedRowKeys.value}, handleSuccess);
   }

  async function onFAPIAOExport() {
    return defHttp.post({url:getExportFAOPIAOUrl, data: {ids: selectedRowKeys.value}},{joinParamsToUrl: true}).then((data) => {
      console.log(getToken());
/*      downloadByUrl({
        url: 'http://localhost:3100/eamboot/assets.accountReceive/dbHire/exportFAPIAONext?name='+data+'&access_token='+getToken(),
        target: '_self',
      });*/

     console.log(urlPrefix);
      //let consturl=window.config.host +"/iip/iip-faceserver/faceSystemData/downLoadExport?
      var url=globSetting.apiUrl+'/assets.accountReceive/dbHire/exportFAPIAONext?name='+data;
      var xhr = new XMLHttpRequest();
      xhr.open("get", url, true); // get、post都可
      xhr.responseType = "blob";
      xhr.setRequestHeader("X-Access-Token",getToken()); //加请求头
      xhr.onload = function() {
        if(xhr.status==200){
          let blob = new Blob([this.response], { type: 'application/zip' });
          var a = document.createElement("a")
          var url = window.URL.createObjectURL(blob)
          a.href = url
      //    var farmname=consturl.substring(consturl.length-21)
          a.download = "发票.zip";  // 文件名
          a.click()
          window.URL.revokeObjectURL(url)
        }

      }
      xhr.send();

      handleSuccess();
    });
  }

  async function onFAPIAOExport1(){
   // const { data: bytes } = await defHttp.post({url:getExportFAOPIAOUrl, data: {ids: selectedRowKeys.value},responseType: 'blob'});
/*    const data = await defHttp.post({url:getExportFAOPIAOUrl, data: {ids: selectedRowKeys.value},headers: {
        'Content-Type': 'application/json'
      },responseType:'blob'}, {joinParamsToUrl: true});

    console.log(data);
    //downloadByBase64(data,'test.zip');
   // const blob = new Blob(data)
    downloadByData(data, '发票.zip');
    handleSuccess();*/

    /*const downloadLink = document.createElement('a')
    // 设置下载文件名
    downloadLink.download = 'test.zip'
    downloadLink.style.display = 'none'

    const blob = new Blob(stringToBytes(data))
    downloadLink.href = URL.createObjectURL(blob)
    document.body.appendChild(downloadLink)
    downloadLink.click()
    document.body.removeChild(downloadLink)*/
/*console.log(urlPrefix);

    axios({
      method: 'post',
      url: getExportFAOPIAOUrl,
      data:  {ids: selectedRowKeys.value},
      responseType: 'blob'
    }).then(res => {
      console.log(res.data)
      let blob = new Blob([res.data], {type: 'application/zip'})
      let url = window.URL.createObjectURL(blob)
      const link = document.createElement('a') // 创建a标签
      link.href = url
      link.click()
      URL.revokeObjectURL(url) // 释放内存
    }).catch(err => {
      console.log(err)
    })*/

  }
  function stringToBytes(str) {
    str = unescape(encodeURIComponent(str))
    for (var bytes = [], i = 0; i < str.length; i++)
      bytes.push(str.charCodeAt(i) & 0xFF);
    return bytes;
  }

  /**
    * 成功回调
    */
  function handleSuccess() {
    closeWrapLoading();
      (selectedRowKeys.value = []) && reload();
   }
   function handleImportFAPIAOSuccess(){

   }
   /**
      * 操作栏
      */
  function getTableAction(record){
       return [
         {
           label: '编辑',
           onClick: handleEdit.bind(null, record),
         }
       ]
   }
     /**
        * 下拉操作栏
        */
  function getDropDownAction(record){
       return [
         {
           label: '详情',
           onClick: handleDetail.bind(null, record),
         }, {
           label: '删除',
           popConfirm: {
             title: '是否确认删除',
             confirm: handleDelete.bind(null, record),
           }
         }
       ]
   }

  function handleFile(file){
    console.log(file);
    let tempArr = file.split('.')
    let imgList = ['png','jpg','gpeg','bmp','webp']
    let suffix = tempArr[tempArr.length-1]
    let isImg = imgList.some((item)=>{
      return item == suffix
    })
    if (isImg) {
      createImgPreview({ imageList: [file], maskClosable: true });
    }
    else if(suffix=='pdf'){
      return new Promise((resolve, reject) => {
                let blob = null;
                let xhr = new XMLHttpRequest();
                xhr.open("GET", file,true);
                xhr.responseType = "blob";
                xhr.onload = () => {
                    blob = xhr.response;
                    const blobob = new Blob([blob], { type: 'application/pdf;charset=utf-8' });
                    const href = window.URL.createObjectURL(blobob);
                    window.open(href, 'newWindow');
                    resolve(file);
                };
                xhr.onerror = (e) => {
                    reject(e)
                };
                xhr.send();
      });
    } else {
      window.open(file);
    }
  }

  console.log(111);
  console.log(route);

</script>

<style scoped>

</style>
